from market.models import Strategy
from market.view import View
from market.models import Asset
from market.models import Player

from market.mathView import viewScalarProduct
from market.mathView import viewAdd
from market.mathView import viewMul

# this class contains all the info of the market
# this object is the one given to the view that will display it
class MarketData:

        ###########################################################################################
        # constructor
	def __init__(self):
		self.market = self.getMarketFromDB()
		self.marketView = self.calculateMarketView()
		self.assets = Asset.objects.all()

        ###########################################################################################
	# the market data are recorded in that object using a list [(fundView, mtm)...]
	def getMarketFromDB(self):
		lTmp = []
		for p in Player.objects.all():
			l = Strategy.objects.filter(name=p.mainStrategy)
			if len(l) <> 1:
				return
			v = View()
			v.setViewFromStrategy(l[0])
			lTmp.append((v,0))
		return lTmp

        ###########################################################################################
	# compute the  market price/view on asset according to rule 1
	#########################################################################################################################
        ####### Rule 1: Market prices
        #########################################################################################################################
        #The market price of an asset is:
		# 
		# price_asset = sum_player( strat_asset,player ) / nPlayers
		# 
	def calculateMarketView(self):
		v = View()
		for (fundView,numberAsset) in self.market:
			v = viewAdd(v, fundView)
		# we need to convert to a float to make the division
		return viewMul(v, 1 / float(len(Player.objects.all())))

        ###########################################################################################
	# returns the view of the market
	def getMarketView(self):
		return self.marketView


        ###########################################################################################
        # returns the strategy  value of the player. basicaly the scalar product between the market view and the strategy view.
	def getStrategyMtM(self, view ):
		return viewScalarProduct( self.marketView, view ) / 100

	
	
